搭建一个简单的 Go RESTful 服务

Go RESTful

由于是搭建一个简单的RESTful,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8080", nil)
}
func hello(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
if len(name) == 0 {
name = "Stranger"
}
fmt.Fprintf(w, "Hello, %v", name)
}


func main()

创建hello()函数去处理path/hello的请求
在8080端口创建一个web server监听请求

func hello()

检查请求是否提供name,如果没有就默认为”Stranger”
然后打印欢迎界面

运行结果

curl http://localhost:8080/hello

Hello, Stranger

curl http://localhost:8080/hello?name=kelele67

Hello, kelele67

参考

How To Create A Simple RESTful Service In Go